<template>
  <div class="example3" ref="scrollRef" @scroll="scrollHandle">
    <div
      :style="{
        paddingTop: `${paddingTop}px`,
        paddingBottom: `${paddingBottom}px`
      }"
    >
      <div
        class="example_item"
        v-for="item in subData"
        :key="item.id"
        :style="{ height: itemHeight + 'px' }"
      >
        {{ item.name }}
      </div>
    </div>
  </div>
</template>

<script>
  var allData = [];
  for (let index = 0; index < 500; index++) {
    allData.push({
      id: index,
      name: '行' + (index + 1)
    });
  }
  export default {
    name: '',
    props: {},
    components: {},
    data() {
      return {
        itemHeight: 40,
        allData: allData,
        start: 0,
        count: 30
      };
    },
    computed: {
      totalHeight() {
        return this.itemHeight * this.allData.length;
      },
      subData() {
        return this.allData.slice(this.start, this.start + this.count);
      },
      currentHeight() {
        return this.count * this.itemHeight;
      },
      paddingTop() {
        return this.start * this.itemHeight;
      },
      paddingBottom() {
        return this.totalHeight - this.itemHeight * this.start - this.currentHeight;
      }
    },
    created() {},
    mounted() {},
    methods: {
      scrollHandle() {
        var scrollRef = this.$refs.scrollRef;
        const { scrollTop, clientHeight } = scrollRef;
        if (
          scrollTop + clientHeight >= this.itemHeight * (this.start + this.count) ||
          scrollTop <= this.itemHeight * this.start
        ) {
          const newStart = Math.floor(scrollTop / this.itemHeight);
          this.start = Math.min(this.allData.length - this.count, newStart);
        }
      }
    },
    watch: {},
    filters: {}
  };
</script>

<style scoped lang="scss">
  .example3 {
    width: 300px;
    height: 500px;
    background-color: #fff;
    border: 1px solid #e8e8e8;
    overflow: auto;
    box-sizing: content-box;
  }
  .example_item {
    width: 100%;
    &:nth-child(even) {
      background-color: #e3e3e3;
    }
  }
  .example_content {
    transition: all 0.3;
  }
</style>
